<?php
namespace app\admin\controller;

use app\admin\controller\Base;
use app\common\model\ProductCate;
use \think\Request;
use think\facade\View;
use think\facade\Db;


class Seckill extends Base
{


    /**
     * 秒杀时间列表
     */
    public function seckill(Request $request)
    {

        $whe = [];
        $field = "*";
        $order = "seckill_time asc";
        $data = $this->getMulListLimit("kk_seckill", $whe, $field, $order, 20);
        View::assign("list", $data['list']);
        View::assign("count", $data['count']);
        View::assign("page", $data['page']);
        return View::fetch('Seckill/seckill');

    }

    /**
     * 秒杀时间新增
     */
    public function seckill_add(Request $request)
    {
        if (!$request->isPost()) {
            return View::fetch('Seckill/seckill_add');
        } else {
            $data = input("post.");
            if (empty($data['seckill_time'])) {
                return $this->err('请输入分类');
            }
//            if (empty($data['goods_num'])) {
//                return $this->err('请输入限购数量');
//            }
//            if (RegInt($data['goods_num'])) {
//                return $this->err('限购数量请大于0');
//            }
            $t = Db::name('kk_seckill')
                ->where(['seckill_time' => $data['seckill_time']])
                ->find();
            if ($t) {
                return $this->err('分类已存在');
            }
            $data['addtime'] = time();
            $res = Db::name('kk_seckill')->insert($data);
            if ($res) {
                return $this->succ("添加成功");
            } else {
                return $this->err("添加失败");
            }
        }
    }

    /**
     * 秒杀时间编辑
     */
    public function seckill_edit(Request $request)
    {
        if (!$request->isPost()) {
            $id = request()->param('id/d', 0);
            $info = Db::name('kk_seckill')->where(['id' => $id])->find();
            if (!$info) {
                return $this->err('参数错误');
            }
            View::assign('info', $info);
            return View::fetch('Seckill/seckill_edit');
        } else {
            $data = input("post.");
            if (empty($data['id'])) {
                return $this->err('参数错误1');
            }
            if (empty($data['seckill_time'])) {
                return $this->err('请输入分类');
            }

            $info_u = Db::name('kk_seckill')->where(['id' => $data['id']])->find();
            if (!$info_u) {
                return $this->err('参数错误2');
            }
            unset($data['id']);

            $t = Db::name('kk_seckill')
                ->where('id', '<>', $info_u['id'])
                ->where(['seckill_time' => $data['seckill_time']])
                ->find();
            if ($t) {
                return $this->err('分类已存在');
            }
            $data['update_time'] = time();
            $res = Db::name('kk_seckill')->where(['id' => $info_u['id']])->update($data);
            if ($res) {
                return $this->succ("编辑成功");
            } else {
                return $this->err("编辑失败");
            }
        }
    }

    /**
     * 秒杀时间删除
     */
    public function seckill_status(Request $request)
    {
        $data = $request->post();
        if (empty($data['id'])) {
            return $this->err("请选择操作的数据");
        }
        $id = $data['id'];
        Db::startTrans();
        $res = [];
        $res[] = Db::name('kk_seckill')
            ->where('id','in',$id)
            ->delete();
        if (resCheck($res)) {
            Db::commit();
            return $this->succ("操作成功");
        } else {
            Db::rollback();
            return $this->err("操作失败");
        }
    }


    /**
     * 商品列表
     * @param $title 商品名称
     * @param $status 0上架 1下架
     */
    public function seckill_product(Request $request)
    {
        $keyword = trim(input('get.keyword'));
        $status = trim(input('get.status'));
        $whe = array();
        #商品名称
        if ($keyword) {
            $whe[] = ['title','like','%'.$keyword.'%'];
        }
        #上架 下架
        if ($status === '0' || $status === '1') {
            $whe[] = ['status','=',$status];
        }
        $field = "*";
        $order = "id desc";
        $data = $this->getMulListLimit("kk_product", $whe, $field, $order, 10);
        foreach ($data['list'] as $k => $v) {
            #商品规格
            $spec_info = Db::name('kk_product_spec')->field('price,seckill_price')->order('price asc')->where(['pro_id' => $v['id']])->find();
            $data['list'][$k]['price'] = $spec_info['price'];#售价
            $data['list'][$k]['seckill_price'] = $spec_info['seckill_price'];#秒杀价
            #秒杀时间段
//            $seckill_time = Db::name('kk_seckill')->field('seckill_time')->where(['id' => $v['seckill_id']])->value('seckill_time');
//            $data['list'][$k]['seckill_time'] = $seckill_time;

            $data['list'][$k]['cate_name1'] = ProductCate::where('id','=',$v['cate_id1'])->value('title');
            $data['list'][$k]['cate_name2'] = ProductCate::where('id','=',$v['cate_id2'])->value('title');
        }
        View::assign("list", $data['list']);
        View::assign("count", $data['count']);
        View::assign("page", $data['page']);
        return View::fetch('Seckill/seckill_product');
    }
    /**
     * 获取二级分类
     */
    public function getCate(Request $request){
        $cate_id = $request->param('cate_id');
        $w[] = ['pid','=',$cate_id];
        $w[] = ['status','=','1'];
        $cate = ProductCate::getAllList($w,'id,title');
        $html = '<div class="layui-input-inline cate2"><select name="cate_id2" lay-verify="">';
//        $html .= '<option value="0">请选择</option>';
        foreach ($cate as $k => $v) {

            $html .= '<option value="'.$v['id'].'">'.$v['title'].'</option>';
        }
        $html .= '</select></div>';
        return $html;
    }
    /**
     * 商城商品新增
     */
    public function seckill_product_add(Request $request)
    {
        if (!$request->isPost()) {
            $w= [];
            $w[] = ['pid','=','0'];
            $w[] = ['status','=','1'];
            $cate = ProductCate::getAllList($w,'id,title');
            View::assign('cate',$cate);
            View::assign('newgglist', []);
            return View::fetch('Seckill/seckill_product_add');
        } else {
            $data = input("post.");
            if (empty($data['title'])) {
                return $this->err('请输入商品名称');
            }
//            if (empty($data['seckill_id'])) {
//                return $this->err('请选择商品分类');
//            }
            if ($data['status'] != 0 && $data['status'] != 1) {
                return $this->err('商品状态选择错误');
            }
            if (empty($data['image'])) {
                return $this->err('请上传商品主图');
            }
            if (empty($data['detail_image'])) {
                return $this->err('请上传商品详情图');
            }
            if (empty($data['content'])) {
                return $this->err('请输入商品详情');
            }
            if (empty($data['spec_data'])) {
                return $this->err('请选择规格');
            }
            if (empty($data['option'])) {
                return $this->err('请设置规格详情');
            }
            if (RegZero($data['sort'])) {
                return $this->err('商品排序输入不合法');
            }
            if (RegZero($data['sale_num'])) {
                return $this->err('商品销量输入不合法');
            }
            if (RegMoney($data['freight'])) {
                return $this->err('运费设置错误');
            }
            #去除空图片
            $detail_image = json_decode($data['detail_image'], true);
            $detail_image_arr = [];
            foreach ($detail_image as $k => $v) {
                if ($v != '') {
                    $detail_image_arr[] = $v;
                }
            }
            if (empty($detail_image_arr)) {
                return $this->err('请上传商品详情图');
            }
            $data['detail_image'] = json_encode($detail_image_arr);
            $data['addtime'] = time();
            unset($data['spec_name']);
            unset($data['option']);
            Db::startTrans();
            $res = [];
            #添加商品
            $res[] = $pro_id = Db::name('kk_product')->insertGetId($data);
            #添加规格
            $newggids = array();
            foreach (input('post.option/a') as $ks => $v) {
                if (empty($v['name'])) {
                    Db::rollback();
                    return $this->err('参数错误');
                }
                if (RegMoney($v['price'])) {
                    Db::rollback();
                    return $this->err('售价最多保留两位小数');
                }
                if (RegMoney($v['seckill_price'])) {
                    Db::rollback();
                    return $this->err('秒杀价最多保留两位小数');
                }
                if (RegInt($v['stock'])) {
                    Db::rollback();
                    return $this->err('库存输入不合法');
                }
                $ggdata = array();
                $ggdata['pro_id'] = $pro_id;
                $ggdata['ks'] = $ks;
                $ggdata['name'] = $v['name'];
                $ggdata['price'] = $v['price'] > 0 ? $v['price'] : 0;
                $ggdata['seckill_price'] = $v['seckill_price'] > 0 ? $v['seckill_price'] : 0;
                $ggdata['stock'] = $v['stock'] > 0 ? $v['stock'] : 0;
                $ggdata['pic'] = $v['pic'] ? $v['pic'] : '';
                #是否存在规格
                $guige = Db::name('kk_product_spec')->where(['pro_id' => $pro_id, 'ks' => $ks])->find();
                if ($guige) {
                    $res[] = Db::name('kk_product_spec')->where(['id' => $guige['id']])->update($ggdata);
                    $ggid = $guige['id'];
                } else {
                    $res[] = $ggid = Db::name('kk_product_spec')->insertGetId($ggdata);
                }
                $newggids[] = $ggid;
            }

            #存在删除
            Db::name('kk_product_spec')->where(['pro_id' => $pro_id])->where('id','not in',$newggids)->delete();
            if (resCheck($res)) {
                Db::commit();
                return $this->succ("添加成功");
            } else {
                Db::rollback();
                return $this->err("添加失败");
            }
        }
    }

    /**
     * 商城商品编辑
     */
    public function seckill_product_edit(Request $request)
    {
        if (!$request->isPost()) {
            $id = request()->param('id/d', 0);
            $info = Db::name('kk_product')->where(['id' => $id])->find();
            if (!$info) {
                $this->err('数据不存在');
            }
            #图片
            $detail_image = $info['detail_image'];
            #规格
            $guigedata = json_decode($info['spec_data'], true);
            #规格小类
            $newgglist = array();
            if ($info) {
                $gglist = Db::name('kk_product_spec')->where(['pro_id' => $info['id']])->select();
                foreach ($gglist as $k => $v) {
                    if ($v['ks'] !== null) {
                        $newgglist[$v['ks']] = $v;
                    } else {
                        $newgglist[$k] = $v;
                    }
                }
            }
            #秒杀时间段
//            $seckill = Db::name('kk_seckill')->order('seckill_time asc')->select();
            //一级分类
            $w= [];
            $w[] = ['pid','=','0'];
            $w[] = ['status','=','1'];
            $cate = ProductCate::getAllList($w,'id,title');
            View::assign('cate',$cate);
            $ww = [];
            $ww[] = ['pid','=',$info['cate_id1']];
            $ww[] = ['status','=',1];
            $cate2 = ProductCate::getAllList($ww,'id,title');

            View::assign('cate2',$cate2);
            View::assign('detail_image_arr', json_decode($detail_image, true));
            View::assign('detail_image', $detail_image);
            View::assign('guigedata', $guigedata);
            View::assign('newgglist', $newgglist);
//            View::assign('seckill', $seckill);
            View::assign('info', $info);
            return View::fetch('Seckill/seckill_product_edit');
        } else {
            $data = input("post.");
            if (empty($data['id'])) {
                return $this->err('参数错误1');
            }
            $info_u = Db::name('kk_product')->where(['id' => $data['id']])->find();
            if (!$info_u) {
                return $this->err('参数错误2');
            }
            if (empty($data['title'])) {
                return $this->err('请输入商品名称');
            }
           
//            if (empty($data['seckill_id'])) {
//                return $this->err('请选择商品分类');
//            }
            if ($data['status'] != 0 && $data['status'] != 1) {
                return $this->err('商品状态选择错误');
            }
            if (empty($data['image'])) {
                return $this->err('请上传商品主图');
            }
            if (empty($data['detail_image'])) {
                return $this->err('请上传商品详情图');
            }
            if (empty($data['content'])) {
                return $this->err('请输入商品详情');
            }
            if (empty($data['spec_data'])) {
                return $this->err('请选择规格');
            }
            if (empty($data['option'])) {
                return $this->err('请设置规格详情');
            }
            if (RegZero($data['sort'])) {
                return $this->err('商品排序输入不合法');
            }
            if (RegZero($data['sale_num'])) {
                return $this->err('商品销量输入不合法');
            }
            if (RegMoney($data['freight'])) {
                return $this->err('运费请保留两位小数');
            }
            #去除空图片
            $detail_image = json_decode($data['detail_image'], true);
            $detail_image_arr = [];
            foreach ($detail_image as $k => $v) {
                if ($v != '') {
                    $detail_image_arr[] = $v;
                }
            }
            if (empty($detail_image_arr)) {
                return $this->err('请上传商品详情图');
            }
            $data['detail_image'] = json_encode($detail_image_arr);
            $data['update_time'] = time();
            unset($data['spec_name']);
            unset($data['option']);
            unset($data['id']);
            Db::startTrans();
            $res = [];
            #添加商品
            $pro_id = $info_u['id'];
            $res[] = Db::name('kk_product')->where(['id' => $pro_id])->update($data);

            #添加规格
            $newggids = array();
            foreach (input('post.option/a') as $ks => $v) {
                if (empty($v['name'])) {
                    Db::rollback();
                    return $this->err('参数错误');
                }
                if (RegMoney($v['price'])) {
                    Db::rollback();
                    return $this->err('售价最多保留两位小数');
                }
                if (RegMoney($v['seckill_price'])) {
                    Db::rollback();
                    return $this->err('秒杀价最多保留两位小数');
                }
                if (RegInt($v['stock'])) {
                    Db::rollback();
                    return $this->err('库存输入不合法');
                }
                $ggdata = array();
                $ggdata['pro_id'] = $pro_id;
                $ggdata['ks'] = $ks;
                $ggdata['name'] = $v['name'];
                $ggdata['price'] = $v['price'] > 0 ? $v['price'] : 0;
                $ggdata['seckill_price'] = $v['seckill_price'] > 0 ? $v['seckill_price'] : 0;
                $ggdata['stock'] = $v['stock'] > 0 ? $v['stock'] : 0;
                $ggdata['pic'] = $v['pic'] ? $v['pic'] : '';
                $ggdata['time'] = time();
                #是否存在规格
                $guige = Db::name('kk_product_spec')->where(['pro_id' => $pro_id, 'ks' => $ks])->find();
                if ($guige) {
                    $res[] = Db::name('kk_product_spec')->where(['id' => $guige['id']])->update($ggdata);
                    $ggid = $guige['id'];
                } else {
                    $res[] = $ggid = Db::name('kk_product_spec')->insertGetId($ggdata);
                }
                $newggids[] = $ggid;
            }
            #存在删除
            Db::name('kk_product_spec')->where(['pro_id' => $pro_id])->where('id','not in',$newggids)->delete();
            if (resCheck($res)) {
                Db::commit();
                return $this->succ("编辑成功");
            } else {
                Db::rollback();
                return $this->err("编辑失败");
            }
        }
    }


    /**
     * 商品上架 下架 删除
     */
    public function seckill_product_del(Request $request)
    {
        $data = $request->post();
        if (empty($data['id'])) {
            return $this->err("请选择操作的数据");
        }
        $id = $data['id'];
        $status = $request->post('status/d', -1);

        Db::startTrans();
        $res = [];
        if ($status == 0 || $status == 1) {#上架/下架
            $res[] = Db::name('kk_product')
                ->where('id', 'in', $id)
                ->update([
                    'status' => $status,
                    'update_time' => time(),
                ]);
        } else if ($status == 2) {#删除
            $res[] = Db::name('kk_product')
                ->where('id', 'in', $id)
                ->delete();
            $res[] = Db::name('kk_product_spec')
                ->where('pro_id', 'in', $id)
                ->delete();
        } else {
            return $this->err("请求错误");
        }
        if (resCheck($res)) {
            Db::commit();
            return $this->succ("操作成功");
        } else {
            Db::rollback();
            return $this->err("操作失败");
        }
    }


    /**
     * 发货订单记录
     */
    public function send_order(Request $request)
    {
//        dd(11);
        $uid = trim(input('get.uid'));
        $status = trim(input('get.status'));
        $pay_time = trim(input('get.pay_time'));
        $order_no = trim(input('get.order_no'));
        $whe = array();
        #会员id
        if (!empty($uid)) {
            $whe[] = ['user_id', '=', $uid];
        }
        #状态
        if (!empty($status)) {
            $whe[] = ['status', '=', $status];
        } else {
            $whe [] = ['status', '>', 0];
        }
        #订单号
        if (!empty($order_no)) {
            $whe[] = ['order_no', '=', trim($order_no)];
        }
        #支付时间
        if ($pay_time != '') {
            $time = explode(' - ', $pay_time);
            $start_time = strtotime($time[0]);
            $end_time = strtotime($time[1]) - 1;
            if ($start_time > $end_time) {
                $this->err('开始时间不能大于结束时间');
            }
            $whe[] = ['pay_time', 'BETWEEN', array($start_time, $end_time)];
        }
        $order = "id desc";
        $data = $this->getMulListLimit("kk_order", $whe, '*', $order, 10);
        foreach ($data['list'] as $k => &$v) {
            #用户信息
            $user_info = Db::name('user')->field('nickname,headimg')->where(['id'=>$v['user_id']])->find();
            $v['nickname'] = $user_info['nickname'];
            $v['headimg'] = $user_info['headimg'];
            #收货地址
            $address = Db::name('kk_order_send')->where(['order_id' => $v['id']])->find();
            $v['address'] = $address;
            
        }
        View::assign('list', $data['list']);
        View::assign('count', $data['count']);
        View::assign('page', $data['page']);
        return View::fetch("/Seckill/send_order");
    }

    /**
     * 订单详情
     */
    public function send_order_detail(Request $request)
    {
        $id = Request()->param('id/d', 0);
        $info = Db::name('kk_order')->where(['id' => $id])->find();
        if (!$info) {
            return $this->err('参数错误');
        }
        $goods_data = Db::name('kk_order_good')
            ->where(['order_id' => $id])
            ->select();
        #用户信息
        $info['user_info'] = Db::name('user')
            ->field('id,nickname,headimg')
            ->where(['id' => $info['user_id']])
            ->find();
        #收货地址信息
        $info['address'] = Db::name('kk_order_send')
            ->where(['order_id' => $info['id']])
            ->find();

        View::assign("info", $info);
        View::assign('list', $goods_data);
        View::assign('count', count($goods_data));
        return View::fetch('Seckill/send_order_detail');
    }


    /**
     * 订单发货
     */
    public function send_order_deliver(Request $request)
    {
        if (!request()->isPost()) {
            $id = request()->param('id/d', 0);
            $info = Db::name('kk_order')->where(array('id' => $id))->find();
            if (!$info) {
                return $this->err('参数错误');
            }
            View::assign('info', $info);
            return View::fetch("/Seckill/send_order_deliver");
        } else {
            $data = request()->param();
            if (empty($data['delivery_name'])) {
                return $this->err('请输入物流公司');
            }
            if (empty($data['delivery_no'])) {
                return $this->err('请输入物流单号');
            }
            if (empty($data['id'])) {
                return $this->err('参数错误1');
            }
            #订单信息
            $order_info = Db::name('kk_order')->where(array('id' => $data['id']))->find();
            if (!$order_info) {
                return $this->err('参数错误3');
            }
            #物流信息
            $send_info = Db::name('kk_order_send')->where(array('order_id' => $data['id']))->find();
            if (!$send_info) {
                return $this->err('参数错误4');
            }
            if ($order_info['status'] == 2) {
                return $this->err('已发货,请勿重复操作');
            }
            if ($order_info['status'] != 1) {
                return $this->err('状态异常');
            }
            Db::startTrans();
            $res = [];
            $res[] = Db::name('kk_order')->where(['id' => $order_info['id']])->update([
                'status' => 2,
                'deliver_time' => time(),
            ]);
            $res[] = Db::name('kk_order_send')->where(['id' => $send_info['id']])->update([
                'delivery_name' => $data['delivery_name'],
                'delivery_no' => $data['delivery_no'],
            ]);
            if (resCheck($res)) {
                Db::commit();
                return $this->succ('发货成功');
            } else {
                Db::rollback();
                return $this->err('发货失败');
            }
        }


    }

    /**
     * 查看物流
     */
    public function send_order_logistics()
    {
        $id = Request()->param('id/d', 0);
        $info = Db::name('kk_order_send')->where(['order_id' => $id])->find();
        if (!$info) {
            return $this->err('参数错误');
        }
        $mobile = substr($info['shou_mobile'],-4);
        $wuliu = getcourier($info['delivery_no'].':'.$mobile,$info['delivery_name']);
        if($wuliu['code'] != 0){
            return $this->err('未找到物流信息');
        }
        $data = $wuliu['result']['list'];
        View::assign("data", $data);
        return View::fetch('Seckill/send_order_logistics');
    }
    
    /**
     * 签到奖励列表
     */
    public function sign_set()
    {
        $data = Db::name('kk_sign')->select();
        View::assign("list", $data);
        View::assign("count", count($data));
        return View::fetch('Seckill/sign_set');
    }

    /**
     * 签到奖励编辑
     */
    public function sign_set_edit()
    {
        if (request()->isGet()) {
            $id = request()->param('id/d', 0);
            $info = Db::name('kk_sign')->where(['id' => $id])->find();
            if (!$info) {
                return $this->err('请求参数错误');
            }
            View::assign('info', $info);
            return View::fetch('Seckill/sign_set_edit');
        } else {
            $data = request()->param();
            if (empty($data['id'])) {
                return $this->err('请求参数错误');
            }
            $info = Db::name('kk_sign')->where(['id' => $data['id']])->find();
            if (!$info) {
                return $this->err('请求参数错误');
            }
            if (RegZero($data['money'])) {
                return $this->err('奖励积分请保留整数');
            }
            $res = Db::name('kk_sign')->where(['id' => $data['id']])->update([
                'money' => $data['money'],
                'update_time' => time(),
            ]);
            if ($res) {
                return $this->succ('操作成功');
            } else {
                return $this->err('操作失败');
            }
        }
    }

    /**
     * 签到记录
     */
    public function sign_log()
    {
        $uid = trim(input('get.uid'));
        $addtime = trim(input('get.addtime'));
        $whe = array();
        #用户UID
        if (!empty($uid)) {
            $whe[] = ['uid','=',$uid-888];
        }
        #签到时间
        if ($addtime) {
            $addtime = explode(' - ', $addtime);
            $start_time = strtotime($addtime[0]);
            $end_time = strtotime($addtime[1]) - 1;
            $whe[] = ['addtime','BETWEEN',[$start_time, $end_time]];
        }
        $order = "id desc";
        $data = $this->getMulListLimit("kk_sign_log", $whe, '*', $order, 10);
        foreach ($data['list'] as &$v){
            $user_info = Db::name('user')->field('nickname,headimg')->where('id',$v['uid'])->find();
            $v['nickname'] = $user_info['nickname'];
            $v['headimg'] = $user_info['headimg'];
        }
        View::assign("list", $data['list']);
        View::assign("count", $data['count']);
        View::assign("page", $data['page']);
        return View::fetch('Seckill/sign_log');
    }    

}